package com.xx.servlet.model;

import com.xx.bean.User;
import com.xx.service.impl.UserServiceImpl;
import com.xx.servlet.base.ModelBaseServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserServlet extends ModelBaseServlet {
    private UserServiceImpl userService = new UserServiceImpl();

    public void toLoginPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        processTemplate("user/login", request, response);
    }

    /**
     * 处理登录校验
     */
    public void doLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User(null, username, password, null);
        try {
            // 登录成功
            User loginUser = userService.doLogin(user);
            req.getSession().setAttribute("loginUser",loginUser);
            processTemplate("user/login_success.html",req,resp);
        } catch (Exception e) {
            req.setAttribute("e","用户名密码错误");
            processTemplate("user/login",req,resp);
        }
    }

    /**
     * 去注册页面
     * */
    public void toRegisterPage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        processTemplate("user/regist",request,response);
    }
    public void doRegister(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        User user = new User(null,username,password,email);

        try{
            userService.doRegister(user);
//            resp.sendRedirect(req.getContextPath()+"/pages/user/regist_success.html");
            processTemplate("user/regist_success.html",req,resp);
        }catch (Exception e){
//            resp.getWriter().write("注册失败,用户名已存在");
            req.setAttribute("error","用户名已存在");
            processTemplate("user/regist",req,resp);
        }
    }


    /**
     * 退出登录
     * */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath()+"/index.html");
    }
}
